﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Threading;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
using System.Timers;

namespace 匿名方法Test3
{

    [Serializable]
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    class Program1
    {
        static void Main1(string[] args)
        {
            //// 创建一个Person对象
            //Person person = new Person { Name = "John", Age = 30 };

            //// 序列化Person对象到文件
            //IFormatter formatter = new BinaryFormatter();
            //Stream stream = new FileStream("person.bin", FileMode.Create, FileAccess.Write, FileShare.None);
            //formatter.Serialize(stream, person);
            //stream.Close();

            //// 从文件反序列化Person对象
            //stream = new FileStream("person.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
            //Person personCopy = (Person)formatter.Deserialize(stream);
            //stream.Close();
            //Console.WriteLine($"Name: {personCopy.Name}, Age: {personCopy.Age}");


            //byte[] data = { 0xCD, 0xCC, 0x88, 0x41 };

            //// 转换为浮点数
            //float result = BytesToFloatBigEndian(data);
            //Console.WriteLine($"结果: {result}");  // 输出结果：17.325


            string sid = "0000^123456";
            if (sid.StartsWith("0000"))
            {
                sid = sid.Substring(4);
            }
            Console.ReadLine();
        }

        public static float BytesToFloatBigEndian(byte[] bytes)
        {
            if (bytes.Length != 4)
                throw new ArgumentException("必须提供4字节数据");

            // 大端序需反转字节数组（转为小端序）
            //Array.Reverse(bytes);
            return BitConverter.ToSingle(bytes, 0);
        }
    }

    public class ReturnDataModel2
    {
        public bool success { get; set; }
        public int code { get; set; }
        public string message { get; set; }
        public Data data { get; set; }
        public string tipType { get; set; }
        public class Data
        {
            public int recID { get; set; }
            public string taskNum { get; set; }
        }
    }

    public class AsyncWrapper
    {
        // 同步方法
        public static int SyncMethod()
        {
            Thread.Sleep(2000);
            return 42;
        }

        // 异步包装
        public static async Task<int> SyncMethodAsync()
        {
            return await Task.Run(() => SyncMethod());
        }

        // 调用示例
        public static async Task Demo()
        {
            Console.WriteLine("开始异步调用...");
            int result = await SyncMethodAsync();
            Console.WriteLine($"结果: {result}");
        }
    }

    class Program
    {
        static System.Timers.Timer timerDelete = new System.Timers.Timer();
        static int num = 0;
        static void Main(string[] args)
        {
            //timerDelete.Interval = 5000; // 设置为每5秒触发一次
            //timerDelete.Elapsed += Timer_Elapsed; ;
            //timerDelete.Start();

            //TestDirName();
            //DebugHa2();
            //TestDigestResponse();
            //ParseResponseAuth("");

            //TestUint();
            //Dictionary<string, string> listTempPicFullName = new Dictionary<string, string>();
            //listTempPicFullName.Add("name1", DateTime.Now.ToString("yyyyMMddHHmmssfff"));
            //listTempPicFullName.Add("name2", DateTime.Now.ToString("yyyyMMddHHmmssfff"));
            //Console.WriteLine("listTempPicFullName = " + string.Join(",", listTempPicFullName.Keys));
            //string filetimeL = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            //string filetimed_FormatedL = filetimeL.Substring(0, 4) + "-" + filetimeL.Substring(4, 2) + "-" + filetimeL.Substring(6, 2) + " " + filetimeL.Substring(8, 2) + ":" + filetimeL.Substring(10, 2) + ":" + filetimeL.Substring(12, 2);
            //if (DateTime.TryParse(filetimed_FormatedL, out DateTime dtDateL))
            //{
            //    Console.WriteLine(dtDateL);
            //}
            //    Console.Read();

            //AES.AESDecrypt128();
            // 创建一个Timer对象

            //timer.Elapsed += OnTimedEvent; // 注册事件处理程序
            //timer.AutoReset = true; // 设置是否重复触发
            //timer.Enabled = true; // 启动定时器

            //string s = "{\"success\":true,\"code\":0,\"message\":\"Processed\",\"tipType\":1,\"data\":{\"recID\":19901,\"taskNum\":\"202505080909\"}}";
            //ReturnDataModel2 m = JsonConvert.DeserializeObject<ReturnDataModel2>(s);

            // 测试浅拷贝
            Person original = new Person
            {
                Name = "Alice",
                Address = new Address { City = "New York" }
            };

            //Person copy = original.ShallowCopy();

            // 修改拷贝对象的引用类型字段
            //copy.Address.City = "Los Angeles";
            //copy.Name = "Tom";


            //Console.WriteLine(original.Address.City); // 输出 "Los Angeles"（原对象也被修改）
            //Console.WriteLine(original.Name);
            //Console.WriteLine(object.ReferenceEquals(original.Name,copy.Name));

            //Person copy2 = original.DeepCopy();
            //copy2.Address.City = "Los Angeles2";
            //copy2.Name = "Tom2";

            //Console.WriteLine(original.Address.City); // 输出 "Los Angeles"（原对象也被修改）
            //Console.WriteLine(original.Name);

            //Person copy3 = DeepCopy(original);
            //copy3.Address.City = "Los Angeles3";
            //copy3.Name = "Tom3";

            //Console.WriteLine(original.Address.City); // 输出 "Los Angeles"（原对象也被修改）
            //Console.WriteLine(original.Name);
            //Console.WriteLine(object.ReferenceEquals(original.Name, copy2.Name));

            ParseResponseAuth("");

            Console.ReadKey();
        }

        [Serializable]
        public class Person
        {
            public string Name;
            public Address Address; // Address 是引用类型

            public Person ShallowCopy()
            {
                return (Person)this.MemberwiseClone(); // 浅拷贝
            }

            public Person DeepCopy()
            {
                Person copy = (Person)this.MemberwiseClone();
                copy.Address = new Address { City = this.Address.City }; // 手动复制引用对象
                return copy;
            }
        }
        [Serializable]
        public class Address
        {
            public string City;
        }

        public static T DeepCopy<T>(T obj)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, obj);
                stream.Position = 0;
                return (T)formatter.Deserialize(stream);
            }
        }

        


        
        static System.Timers.Timer timer = new System.Timers.Timer(1000); // 每1000ms触发一次
        private static async void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            try
            {
                if (num == 10)
                {
                    timer.Stop();
                    return;
                }
                Console.WriteLine("timer调用开始...");
                timer.Stop();
                await AsyncWrapper.Demo();
                Console.WriteLine("timer调用结束...");
                num++;
                timer.Start();
            }
            catch (Exception)
            {

                throw;
            }
            timer.Start();
        }

        static void TestUint()
        {
            uint a = uint.MaxValue;
            Console.WriteLine(a);
            Console.WriteLine(a+1);
        }


        private static string ParseResponseAuth(string wwwAuthHeader)
        {
            //wwwAuthHeader = "Digest realm=\"iasserver\",qop=\"auth\",nonce=\"c3pOb25jZToxMDg1MTQ4MDgy\",opaque=\"c3pPcGFxdWU6IDEwODUxNDgwODI = \"";
            //var pattern = @"realm=""([^""]*)"",qop=""([^""]*)"",nonce=""([^""]*)"",algorithm=""([^""]*)"",stale=""([^""]*)""";
            wwwAuthHeader = "Digest realm=\"testrealm @host.com\", qop=\"auth\", nonce=\"MTc0Njg1MDQ2NTU5MzplYjdiYzBiYzkzNzllZjg5YzEyOTk4ZGUxZmIzM2I1Nw == \"";
            //var pattern = @"realm=""([^""]*)"",qop=""([^""]*)"",nonce=""([^""]*)"",opaque=""([^""]*)""";
            var pattern = @"realm=""([^""]*)"", qop=""([^""]*)"", nonce=""([^""]*)""";
            var match = Regex.Match(wwwAuthHeader, pattern);
            if (!match.Success)
            {
                return null;
            }

            // 从正则匹配中提取参数
            var realm = match.Groups[1].Value;
            var qop = match.Groups[2].Value;
            var nonce = match.Groups[3].Value;

            //var opaque = match.Groups[4].Value;
            //var algorithm = match.Groups[4].Value;
            //var stale = match.Groups[5].Value;

            // 生成16位客户端UUID（基于时间戳）
            var cnonce = DateTime.Now.ToString("yyyyMMddHHmmssfff").Substring(0, 16);
            const string method = "POST";
            const string url = "/VIID/System/Register222";

            // 假设存在的摘要生成方法
            var response = GenerateDigestAuthResponse("admin", realm, "admin",
                                                    method, url, nonce, qop, cnonce);

            // 构建认证头信息
            var authheadInfo = new StringBuilder(wwwAuthHeader)
                .AppendFormat(",username=\"{0}\",passwd=\"{1}\",url=\"{2}\",response=\"{3}\",nc={4},cnonce=\"{5}\",algorithm=\"MD5\"",
                            "admin",
                            "admin",
                            url,
                            response,
                            mNc,
                            cnonce)
                .ToString();

            return authheadInfo;
        }
        private static int mInNc = 0; // 计数器
        private static string mNc = "00000000"; // 当前nc值
        public static string GenerateDigestAuthResponse(string username, string realm, string password, string method, string uri, string nonce, string qop, string cnonce)
        {
            // 生成HA1 = MD5(username:realm:password)
            string ha1Input = $"{username}:{realm}:{password}";
            string ha1 = ComputeMd5Hex(ha1Input);

            // 生成HA2 = MD5(method:uri)
            string ha2Input = $"{method}:{uri}";
            string ha2 = ComputeMd5Hex(ha2Input);

            // 构建响应字符串
            string responseInput;
            if (string.IsNullOrEmpty(qop))
            {
                responseInput = $"{ha1}:{nonce}:{ha2}";
            }
            else
            {
                // 递增并更新nc值
                Interlocked.Increment(ref mInNc);
                mNc = mInNc.ToString("x8"); // 转换为8位十六进制

                responseInput = $"{ha1}:{nonce}:{mNc}:{cnonce}:{qop}:{ha2}";
            }
            // 计算最终响应值
            return ComputeMd5Hex(responseInput);
        }






























        public static void TestDigestResponse1()
        {
            string response = GenerateDigestAuthResponse(
                username: "admin",
                realm: "testrealm@host.com",
                password: "secret",
                method: "POST",
                uri: "/api",
                nonce: "dcd98b7102dd2f0e8b11d0f600bfb0c093",
                qop: "auth",
                cnonce: "0a4f113b",
                nc: "00000000"  // 明确指定 nc
            );

            string expected = "a139c1cf0ee2c8d15b019a24977b9e89";
            Console.WriteLine($"response:{response}");
            bool isEqual = response == expected;  // 现在应为 true
        }

        public static void TestDigestResponse()
        {
            string response = GenerateDigestAuthResponse(
                username: "admin",
                realm: "testrealm@host.com",
                password: "secret",
                method: "POST",
                uri: "/api",
                nonce: "dcd98b7102dd2f0e8b11d0f600bfb0c093",
                qop: "auth",
                cnonce: "0a4f113b",
                nc: "00000000"
            );

            string expected = "a139c1cf0ee2c8d15b019a24977b9e89";
            Console.WriteLine($"response:{response}");
            bool isEqual = response == expected; // 现在应返回 true
        }
        public static void DebugHa2()
        {
            string input = "POST:/api:d41d8cd98f00b204e9800998ecf8427e";
            string ha2 = ComputeMd5Hex(input);
            Console.WriteLine(ha2); // 应输出 "c9e15c1ed06baf887ceec36c43d4d5cd"
        }
        public static string GenerateDigestAuthResponse(
    string username, string realm, string password,
    string method, string uri, string nonce,
    string qop, string cnonce, string nc = "00000000")
        {
            // 计算 HA1 = MD5(username:realm:password)
            string ha1 = ComputeMd5Hex($"{username}:{realm}:{password}");
            Console.WriteLine($"ha1:{ha1}");
            // 计算 HA2 = MD5(method:uri:MD5(requestBody))
            string requestBodyHash = ComputeMd5Hex(""); // 假设请求体为空
            string ha2Input = $"{method}:{uri}:{requestBodyHash}";
            Console.WriteLine($"ha2Input:{ha2Input}");
            string ha2 = ComputeMd5Hex(ha2Input);
            Console.WriteLine($"ha2:{ha2}");
            // 构建响应输入
            string responseInput = $"{ha1}:{nonce}:{nc}:{cnonce}:{qop}:{ha2}";
            return ComputeMd5Hex(responseInput);
        }

        /// <summary>
        /// 计算字符串的 MD5 哈希值（小写十六进制）
        /// </summary>
        private static string ComputeMd5Hex(string input)
        {
            using (var md5 = MD5.Create())
            {
                byte[] inputBytes = Encoding.UTF8.GetBytes(input);
                byte[] hashBytes = md5.ComputeHash(inputBytes);

                StringBuilder sb = new StringBuilder(32);
                foreach (byte b in hashBytes)
                {
                    sb.Append(b.ToString("x2")); // 强制两位小写十六进制
                }
                return sb.ToString();
            }
        }

        static void TestDirName()
        {
            string path = @"D:\desktop\Mine\喀什\卡口";
            FileSystemInfo directorypath = new DirectoryInfo(path);
            DirectoryInfo dir = directorypath as DirectoryInfo;
            FileSystemInfo[] files = dir.GetFileSystemInfos();
            char[] QuTou = { ' ', '\\' };
            string p = @"D:\desktop\Mine\喀什\卡口\20250407";
            for (int i = 0; i < files.Length; i++)
            {
                FileInfo NextFile = files[i] as FileInfo;
                
                string FTPremotePath = p.Replace(path, "").TrimStart(QuTou);
                FTPremotePath = FTPremotePath.Substring(FTPremotePath.Length - 8, 8);
                Console.WriteLine(FTPremotePath);
            }

            Console.ReadKey();
        }

        static void DeleteEmptySubdirectories(string parentDir)
        {
            foreach (string subDir in Directory.GetDirectories(parentDir))
            {
                DeleteEmptySubdirectories(subDir); // 先处理子目录
                if (IsDirectoryEmpty(subDir))
                {
                    try
                    {
                        Directory.Delete(subDir);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"已删除空目录：{ex}");
                    }
                    
                }
            }
        }

        static bool IsDirectoryEmpty(string path)
        {
            return Directory.GetFiles(path).Length == 0
                && Directory.GetDirectories(path).Length == 0;
        }

        /// <summary>
        /// 定时器上传数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                timerDelete.Stop();
                Stopwatch sw = Stopwatch.StartNew();
                string targetDir = @"H:\TestPicPath\TestDelete"; // 替换为你的目标目录
                DateTime today = DateTime.Today;
                int _batchSize = 100;
                var files = Directory.EnumerateFiles(targetDir, "*.*", SearchOption.AllDirectories)
                .Where(f => ShouldDelete(f, today));

                int processed = 0;
                List<string> currentBatch = files.Skip(processed).Take(_batchSize).ToList();

                while (currentBatch.Any())
                {
                    foreach (var file in currentBatch)
                    {
                        try
                        {
                            File.Delete(file);
                            Console.WriteLine($"已删除: {file}");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"删除失败: {file}, 错误: {ex.Message}");
                        }
                    }
                    processed += _batchSize;
                    currentBatch = files.Skip(processed).Take(_batchSize).ToList();
                }
                // 递归删除所有空子目录
                DeleteEmptySubdirectories(targetDir);

                sw.Stop();
                Console.WriteLine($"耗时：{sw.ElapsedMilliseconds}毫秒");
                Console.WriteLine("操作完成");
                timerDelete.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                timerDelete.Start();
            }
        }

        private static bool ShouldDelete(string file, DateTime today) =>
       new FileInfo(file).CreationTime.Date <= today;


    }

    public class FileCleaner
    {
        private readonly string _targetDir;
        private readonly int _batchSize;

        public FileCleaner(string targetDir, int batchSize = 200)
        {
            _targetDir = targetDir;
            _batchSize = batchSize;
        }

        

        // 判断是否为 JPG 文件
        private bool IsJpegFile(string path) =>
            path.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) ||
            path.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase);

        // 判断是否应删除
        private bool ShouldDelete(string file, DateTime today) =>
            new FileInfo(file).CreationTime.Date < today.Date;



        
    }

    public class AES
    {
        /// <summary>
        /// AES解密128位
        /// </summary>
        /// <param name="text"></param>
        /// <param name="password"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static void AESDecrypt128()
        {
            try
            {
                string text = "U2FsdGVkX1/lFvM8UFyyke+QpYEBWfEw9UVjSa5Sl6Lr4s8rNYCPvKTpXZ/0qCITQnNQmqV5Z3qVmOlP3SWmvA==";
                string password = "b3465ded7835ddf8";
                string iv ="65b74123e65aec3f";
                RijndaelManaged rijndaelCipher = new RijndaelManaged();
                rijndaelCipher.Mode = CipherMode.CBC;
                rijndaelCipher.Padding = PaddingMode.PKCS7;
                rijndaelCipher.KeySize = 128;
                rijndaelCipher.BlockSize = 128;
                byte[] encryptedData = Convert.FromBase64String(text);
                byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password);
                byte[] keyBytes = new byte[16];
                int len = pwdBytes.Length;
                if (len > keyBytes.Length) len = keyBytes.Length;
                System.Array.Copy(pwdBytes, keyBytes, len);
                rijndaelCipher.Key = keyBytes;
                byte[] ivBytes = System.Text.Encoding.UTF8.GetBytes(iv);
                rijndaelCipher.IV = ivBytes;
                ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
                byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
                string str_return_AESDecrypt128 = Encoding.UTF8.GetString(plainText);

                string errorcodeL = "";
                string messageL = "";
                try
                {
                    if (str_return_AESDecrypt128 != "")
                    {
                        try
                        {
                            JObject jo = (JObject)JsonConvert.DeserializeObject(str_return_AESDecrypt128);
                            errorcodeL = (jo["errorCode"].ToString()).Trim();
                            messageL = (jo["message"].ToString()).Trim(); //(jo["result"]["djbh"].ToString()).Trim();
                        }
                        catch (Exception er)
                        {
                            errorcodeL = "";
                            messageL = "";
                        }
                    }

                    if (errorcodeL == "0")// && result_djbh == dic_PicFullName_djbh[NextFile.FullName])
                    {
                    }
                    else//用记录失败信息
                    {
                    }
                }
                catch (Exception er)
                {
                }
            }
            catch (Exception ex)
            {
               
                
            }
        }
    }

    

}
